package com.cy.mapSort;

import java.security.KeyStore.Entry;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.print.attribute.standard.RequestingUserName;

/**
 * TODO(按map中存放的User的age排序)
 * @author changyuan
 * @date 2018年10月9日 下午4:59:13
 * @Copyright: 2018 www.birdsh.com Inc. All rights reserved.
 */
public class MapSort {

    public static HashMap<String, User> mapSort(Map<String, User> target){
        LinkedHashMap<String,User> resultMap = new LinkedHashMap<String,User>();
        System.out.println(target);
        Set<java.util.Map.Entry<String, User>> targetSet = target.entrySet();
        List<java.util.Map.Entry<String, User>> targetList = new ArrayList(targetSet);
        Collections.sort(targetList,
            new Comparator<java.util.Map.Entry<String, User>>() {
                public int compare(java.util.Map.Entry<String, User> o1, java.util.Map.Entry<String, User> o2) {
                    return o1.getValue().getAge()-o2.getValue().getAge();
                }      
        });
        for(java.util.Map.Entry<String, User> item : targetList){
            resultMap.put(item.getKey(), item.getValue());
        }
        return resultMap; 
    }
    
    public static void main(String[] args){
        //System.out.println("success!");
        User one = new User("one", 16);
        User two = new User("two", 15);
        User three = new User("three", 17);
        
        HashMap target = new HashMap<String,User>();
        target.put("one", one);
        target.put("two", two);
        target.put("three", three);
        
        System.out.println(MapSort.mapSort(target));
    }
}

class User{
    private String name;
    private Integer age;
       
    public User(String name, Integer age) {
        super();
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "{\"name\":\"" + name + "\",\"age\":\"" + age + "\"}";
    }
    
    
}
